package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session)
    {
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone))
        {
            //生成4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("验证码：{}", code);

            //调用阿里云地API进行发送
            SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);

            //保存验证码到session中，为了校验
//            session.setAttribute(phone, code);

            ////将生成的验证码缓存到redis,有效期5min
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }


        return R.error("短信发送失败");
    }


    /**
     * 发送手机验证码
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session)
    {
        log.info(map.toString());

        //从map获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从session中获取保存的验证码，并比对
//        Object codeInSession = session.getAttribute(phone);

        ////从redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        if(codeInSession != null && codeInSession.equals(code))
        {
            //如果是新用户，保存到数据库中
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User one = userService.getOne(lambdaQueryWrapper);
            //新用户
            if(one == null)
            {
                //自动注册
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user", one.getId());

            ////如果登录成功，删除验证码的缓存
            redisTemplate.delete(phone);

            return R.success(one);
        }

        return R.error("登录失败");
    }

}
